package com.note.chh.notebook.UI.enjoy;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.Space;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.note.chh.notebook.Adapter.LifestyleAdapter;
import com.note.chh.notebook.Adapter.WeatherAdapter;
import com.note.chh.notebook.Model.WeatherModel;
import com.note.chh.notebook.R;
import com.note.chh.notebook.UI.base.BaseActivity;
import com.note.chh.notebook.UI.dynamic.BaseWeatherType;
import com.note.chh.notebook.UI.dynamic.DynamicWeatherView;
import com.note.chh.notebook.UI.dynamic.FogType;
import com.note.chh.notebook.UI.dynamic.HailType;
import com.note.chh.notebook.UI.dynamic.HazeType;
import com.note.chh.notebook.UI.dynamic.OvercastType;
import com.note.chh.notebook.UI.dynamic.RainType;
import com.note.chh.notebook.UI.dynamic.SandstormType;
import com.note.chh.notebook.UI.dynamic.ShortWeatherInfo;
import com.note.chh.notebook.UI.dynamic.SnowType;
import com.note.chh.notebook.UI.dynamic.SunnyType;
import com.note.chh.notebook.Uitls.ItemDivider;
import com.note.chh.notebook.Uitls.UserUtil;
import com.note.chh.notebook.Uitls.WeatherUtils;
import com.note.chh.notebook.Uitls.gson.GsonImpl;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.note.chh.notebook.MyApplication.currentCity;

//天气界面
public class WeatherActivity extends BaseActivity {


    @BindView(R.id.dynamicWeather)
    DynamicWeatherView dynamicWeatherView;
    @BindView(R.id.spacer)
    Space spacer;
    @BindView(R.id.tv_now_hum)
    TextView tvNowHum;
    @BindView(R.id.layout_details_humidity)
    LinearLayout layoutDetailsHumidity;
    @BindView(R.id.tv_now_pres)
    TextView tvNowPres;
    @BindView(R.id.layout_details_aqi)
    LinearLayout layoutDetailsAqi;
    @BindView(R.id.tv_now_wind_sc)
    TextView tvNowWindSc;
    @BindView(R.id.tv_now_wind_dir)
    TextView tvNowWindDir;
    @BindView(R.id.layout_details_wind)
    LinearLayout layoutDetailsWind;
    @BindView(R.id.layout_details)
    RelativeLayout layoutDetails;
    @BindView(R.id.tv_temp)
    TextView tvTemp;
    @BindView(R.id.tv_weather_string)
    TextView tvWeatherString;
    @BindView(R.id.tv_temp_max)
    TextView tvTempMax;
    @BindView(R.id.tv_temp_min)
    TextView tvTempMin;
    @BindView(R.id.layout_now)
    LinearLayout layoutNow;
    @BindView(R.id.mText_currentCity)
    TextView mTextCurrentCity;
    @BindView(R.id.mRecycle_weather)
    RecyclerView mRecycleWeather;
    @BindView(R.id.mButton)
    Button mButton;
    @BindView(R.id.mImage_weather_icon)
    ImageView mImageWeatherIcon;
    @BindView(R.id.mText_weather)
    TextView mTextWeather;
    @BindView(R.id.mText_sr)
    TextView mTextSr;
    @BindView(R.id.mText_ss)
    TextView mTextSs;
    @BindView(R.id.mText_pop)
    TextView mTextPop;
    @BindView(R.id.mText_uv_index)
    TextView mTextUvIndex;
    @BindView(R.id.mRecycle_lifestyle)
    RecyclerView mRecycleLifestyle;
    @BindView(R.id.mNestedScrollView)
    NestedScrollView mNestedScrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.mLinear_title)
    LinearLayout mLinearTitle;

    private BaseQuickAdapter weatherAdapter, lifestyleAdapter;
    private BaseWeatherType type;

    @Override
    protected int bindLayout() {
        return R.layout.activity_weather;
    }

    @Override
    public void initView() {
//        statusBarVisible(false);

        //沉浸状态栏
        QMUIStatusBar(WeatherActivity.this);

        mRecycleWeather.setLayoutManager(new LinearLayoutManager(this));
        //设置条目分割线
        mRecycleWeather.addItemDecoration(new ItemDivider().setDividerWith(ConvertUtils.dp2px(1)).setDividerColor(getResources().getColor(R.color.line_color)));
        //如果Item高度固定  增加该属性能够提高效率
        mRecycleWeather.setHasFixedSize(true);
        weatherAdapter = new WeatherAdapter(R.layout.item_weather);
        //禁止滑动
        mRecycleWeather.setNestedScrollingEnabled(false);
        //设置加载动画
        weatherAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleWeather.setAdapter(weatherAdapter);


        mRecycleLifestyle.setLayoutManager(new GridLayoutManager(this, 4));
        //设置条目分割线
//        mRecycleLifestyle.addItemDecoration(new ItemDivider().setDividerWith(ConvertUtils.dp2px(1)).setDividerColor(getResources().getColor(R.color.line_color)));
        //如果Item高度固定  增加该属性能够提高效率
        mRecycleLifestyle.setHasFixedSize(true);
        lifestyleAdapter = new LifestyleAdapter(R.layout.item_lifestyle);
        //禁止滑动
        mRecycleLifestyle.setNestedScrollingEnabled(false);
        //设置加载动画
        lifestyleAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRecycleLifestyle.setAdapter(lifestyleAdapter);


        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

//                UserUtil.dLog(" scrollY =  "+scrollY);mLinearTitle
                if (scrollY == 0) {
                    refreshLayout.setEnabled(true);
                }


            }
        });
        mNestedScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_MOVE:
                        if (mNestedScrollView.getScrollY() > 0) {
                            refreshLayout.setEnabled(false);
                        } else {
                            refreshLayout.setEnabled(true);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        refreshLayout.setEnabled(false);
                        break;
                    case MotionEvent.ACTION_DOWN:
                        break;
                }
                return false;
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData();
            }
        });
    }

    @Override
    public void initData() {
        getData();
    }

    //获取数据
    private void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getWeatherData(currentCity);
            }
        }).start();
    }

    @Override
    public void onResume() {
        super.onResume();
        dynamicWeatherView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        dynamicWeatherView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dynamicWeatherView.onDestroy();
    }

    //dialog
    private void previewDynamicWeather() {
        final String[] items = new String[]{"晴（白天）", "晴（夜晚）", "多云", "阴", "雨", "雨夹雪",
                "雪", "冰雹", "雾", "雾霾", "沙尘暴"};
        AlertDialog.Builder builder = new AlertDialog.Builder(WeatherActivity.this);
        builder.setTitle("动态天气预览");
        builder.setCancelable(true);
        builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                switchDynamicWeather(items[which]);
            }
        });
        builder.create().show();

    }

    //选择天气情况对应的动画
    private void switchDynamicWeather(String which) {
        ShortWeatherInfo info = new ShortWeatherInfo();
        info.setCode("100");
        info.setWindSpeed("11");
        switch (which) {
            case "1"://晴（白天）
                info.setSunrise("00:01");
                info.setSunset("23:59");
                info.setMoonrise("00:00");
                info.setMoonset("00:01");
                type = new SunnyType(this, info);
                break;
            case "2"://晴（夜晚）
                info.setSunrise("00:00");
                info.setSunset("00:01");
                info.setMoonrise("00:01");
                info.setMoonset("23:59");
                type = new SunnyType(this, info);
                break;
            case "3"://多云
                info.setSunrise("00:01");
                info.setSunset("23:59");
                info.setMoonrise("00:00");
                info.setMoonset("00:01");
                SunnyType sunnyType = new SunnyType(this, info);
                sunnyType.setCloud(true);
                type = sunnyType;
                break;
            case "4"://阴
                type = new OvercastType(this, info);
                break;
            case "5"://雨
                RainType rainType = new RainType(this, RainType.RAIN_LEVEL_2, RainType.WIND_LEVEL_2);
                rainType.setFlashing(true);
                type = rainType;
                break;
            case "6"://雨夹雪
                RainType rainSnowType = new RainType(this, RainType.RAIN_LEVEL_1, RainType.WIND_LEVEL_1);
                rainSnowType.setSnowing(true);
                type = rainSnowType;
                break;
            case "7"://雪
                type = new SnowType(this, SnowType.SNOW_LEVEL_2);
                break;
            case "8"://冰雹
                type = new HailType(this);
                break;
            case "9"://雾
                type = new FogType(this);
                break;
            case "10"://雾霾
                type = new HazeType(this);
                break;
            case "11"://沙尘暴
                type = new SandstormType(this);
                break;
            default:
                info.setSunrise("00:01");
                info.setSunset("23:59");
                info.setMoonrise("00:00");
                info.setMoonset("00:01");
                SunnyType sunnyType_ = new SunnyType(this, info);
                sunnyType_.setCloud(true);
                type = sunnyType_;
//                type = new SunnyType(this, info);
                break;
        }
        dynamicWeatherView.setType(type);
    }


    @OnClick({R.id.mButton, R.id.mImage_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mButton:
                previewDynamicWeather();
                break;
            case R.id.mImage_back:
                finish();
                break;
        }
    }

    //获取天气数据
    private void getWeatherData(String location) {
        //参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode   字符集 UTF-8
        String param = "key=31fe89e34b6b4102ae9fab81afc7c36d&location=" + location;
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        BufferedReader br = null;
        PrintWriter out = null;
        try {
            //接口地址
            String url = "https://free-api.heweather.com/s6/weather";
            URL uri = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept", "*/*");
            //发送参数
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();
            //接收结果
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            //缓冲逐行读取
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            UserUtil.dLog("---" + sb.toString());
            if (!sb.toString().isEmpty()) {
                spData(sb.toString());
            }
        } catch (Exception ignored) {
        } finally {
            //关闭流
            try {
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e2) {
            }
        }

        refreshLayout.finishRefresh();
    }

    //适配数据
    private void spData(String data) {
        WeatherModel weatherModel = GsonImpl.get().toObject(data, WeatherModel.class);
        List<WeatherModel.HeWeather6Bean> heWeather6 = weatherModel.getHeWeather6();
        WeatherModel.HeWeather6Bean heWeather6Bean = heWeather6.get(0);
        WeatherModel.HeWeather6Bean.BasicBean basic = heWeather6Bean.getBasic();
        final WeatherModel.HeWeather6Bean.NowBean now = heWeather6Bean.getNow();
        final List<WeatherModel.HeWeather6Bean.LifestyleBean> lifestyle = heWeather6Bean.getLifestyle();
        final List<WeatherModel.HeWeather6Bean.DailyForecastBean> daily_forecast = heWeather6Bean.getDaily_forecast();
        final WeatherModel.HeWeather6Bean.DailyForecastBean dailyForecastBean = daily_forecast.get(0);

        final String location = basic.getLocation();//当前区域
        String parent_city = basic.getParent_city();//当前城市
        String fl = now.getFl();
        final String tmp = now.getTmp();//温度
        final String cond_txt = now.getCond_txt();//天气情况
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchDynamicWeather(numCode(cond_txt));
                if (type!=null) {
                    int color = type.getColor();
                    mLinearTitle.setBackgroundColor(color);//设置标题栏背景色
                    refreshLayout.setPrimaryColors(color);//设置刷新主题颜色
                }
                tvTemp.setText(tmp);
                tvWeatherString.setText(cond_txt);
                mTextCurrentCity.setText(currentCity);
                tvTempMax.setText(dailyForecastBean.getTmp_max() + "°C");
                tvTempMin.setText(dailyForecastBean.getTmp_min() + "°C");
                tvNowHum.setText(now.getHum() + "%");
                tvNowPres.setText(now.getPres());
                tvNowWindSc.setText(now.getWind_sc() + "级");
                tvNowWindDir.setText(now.getWind_dir());
                weatherAdapter.setNewData(daily_forecast);
                lifestyleAdapter.setNewData(lifestyle);
                if (dailyForecastBean.getCond_code_d().equals(dailyForecastBean.getCond_code_n())) {
                    mTextWeather.setText(dailyForecastBean.getCond_txt_d());
                } else {
                    mTextWeather.setText(dailyForecastBean.getCond_txt_d() + "转" + dailyForecastBean.getCond_txt_n());
                }
                Glide.with(WeatherActivity.this).load(WeatherUtils.getInstance().getUrl(dailyForecastBean.getCond_code_d())).into(mImageWeatherIcon);
                mTextSr.setText(dailyForecastBean.getSr());
                mTextSs.setText(dailyForecastBean.getSs());
                mTextPop.setText(dailyForecastBean.getPop() + "%");
                for (int i = 0; i < lifestyle.size(); i++) {
                    WeatherModel.HeWeather6Bean.LifestyleBean lifestyleBean = lifestyle.get(i);
                    if (lifestyleBean.getType().equals("uv")) {
                        mTextUvIndex.setText(lifestyleBean.getBrf());
                    }
                }
            }
        });
    }

    //根据天气返回code
    private String numCode(String weather) {
        String numCode = "";
        UserUtil.dLog("time = " + TimeUtils.getNowString().subSequence(11, 13).toString());
        if (weather.contains("晴") && Integer.parseInt(TimeUtils.getNowString().subSequence(11, 13).toString()) >= 6 && Integer.parseInt(TimeUtils.getNowString().subSequence(11, 13).toString()) < 18) {//白天
            numCode = "1";
        } else if (weather.contains("晴")) {//夜晚
            numCode = "2";
        } else if (weather.contains("云")) {
            numCode = "3";
        } else if (weather.contains("阴")) {
            numCode = "4";
        } else if (weather.contains("雨") && weather.contains("雪")) {
            numCode = "6";
        } else if (weather.contains("雨")) {
            numCode = "5";
        } else if (weather.contains("雪")) {
            numCode = "7";
        } else if (weather.contains("冰雹")) {
            numCode = "8";
        } else if (weather.contains("霾")) {
            numCode = "10";
        } else if (weather.contains("雾")) {
            numCode = "9";
        } else if (weather.contains("沙尘暴")) {
            numCode = "11";
        }
        return numCode;
    }

}
